package com.jt.provider.controller;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义限流、降级等异常处理对象
 * */
@Component
@Slf4j
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       BlockException e) throws Exception {
        //设置响应数据编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉客户端响应数据的类型，以及客户端显示内容编码
        httpServletResponse.setContentType("text/html;charset=utf-8");

        //向客户端响应一个json格式的字符串
//        String str = "{\"status\":429,\"message\":\"访问太频繁了，稍等片刻再重试\"}";
        Map<String,Object> map = new HashMap<>();
        map.put("status",429);
        map.put("message","访问频繁，稍等片刻再重试");
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        PrintWriter out = httpServletResponse.getWriter();
        out.print(jsonStr);
        out.flush();
        out.close();
    }
}
